package com.ktjiaoyu.crm.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("执行过滤器init()......");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("执行过滤器doFilter()........");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //验证用户是否登录
        if(httpServletRequest.getSession().getAttribute("loginUser")==null){
            httpServletResponse.setContentType("text/html;charset=UTF-8");
            PrintWriter out = httpServletResponse.getWriter();
            out.print("<script>alert('请先进行登陆， 再进行后续操作！ (Filter 控制)');location.href='"+httpServletRequest.getContextPath()+"/login.jsp';</script>");
            return;
        }
        chain.doFilter(request,response);   //放行请求
    }

    @Override
    public void destroy() {
        System.out.println("执行过滤器destroy().......");
    }
}
